import 'package:flutter/material.dart';
import 'package:flutter_color_plugin/flutter_color_plugin.dart';
import 'package:loading/indicator/ball_pulse_indicator.dart';
import 'package:loading/loading.dart';
import 'package:provider/provider.dart';
import 'package:yw_bapp/dao/common_dao.dart';
import 'package:yw_bapp/model/phone_code_model.dart';
import 'package:yw_bapp/pages/input_code.dart';
import 'package:yw_bapp/provider/login_phone_provider.dart';
import 'package:yw_bapp/utils/check.dart';
import 'package:yw_bapp/utils/show_tip_pop.dart';
import 'package:yw_bapp/widgets/m_btn.dart';
import 'package:yw_bapp/widgets/safe_area_bar_widget.dart';
import 'package:yw_bapp/widgets/show_toast.dart';
import 'package:yw_bapp/widgets/loading_pop_widget.dart';

class PhoneLogin extends StatefulWidget {
  final String title;

  const PhoneLogin({Key key, @required this.title}) : super(key: key);
  @override
  _PhoneLoginState createState() => _PhoneLoginState();
}

class _PhoneLoginState extends State<PhoneLogin> {
  // 手机号控制器
  TextEditingController phoneController = TextEditingController();
  // 下一步按钮的颜色
  bool isActive = false;
  // 按钮点击色
  Color btnActiveColor = ColorUtil.color('#FFC49226');
  // 按钮默认色
  Color btnDefaultColor = ColorUtil.color('#FFDDDDDD');
  // 文字点击色
  Color textActiveColor = Colors.white;
  // 文字默认色
  Color textDefaultColor = ColorUtil.color("#FFAFAFAF");
  // 错误提示的展示
  bool error = false;
  @override
  void initState() {
    // TODO: implement initState
    super.initState();
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: XAppBar(
        statusBarColor: ColorUtil.color('#FFC49226'),
        bgColor: ColorUtil.color('#FFC49226'),
        title: "",
        iconColor: Colors.white,
      ),
      body: Container(
        padding: EdgeInsets.fromLTRB(25, 49.5, 25, 0),
        decoration: BoxDecoration(color: Colors.white),
        child: Column(
          children: <Widget>[
            // 标题
            Row(
              mainAxisAlignment: MainAxisAlignment.start,
              children: <Widget>[
                Text(
                  "手机号${widget.title}",
                  textAlign: TextAlign.start,
                  style: TextStyle(
                      color: ColorUtil.color("#FF333333"),
                      fontSize: 24,
                      fontWeight: FontWeight.bold,
                      decoration: TextDecoration.none),
                ),
              ],
            ),
            // 输入框
            Row(
              children: <Widget>[
                Expanded(
                    flex: 1,
                    child: Padding(
                      padding: EdgeInsets.fromLTRB(0, 50, 0, 50),
                      child: Material(
                        child: TextField(
                            controller: phoneController,
                            keyboardType: TextInputType.number,
                            maxLength: 11,
                            autofocus: false,
                            decoration: InputDecoration(
                                contentPadding: EdgeInsets.all(10),
                                hintText: "请输入手机号",
                                helperText: error ? "*请输入正确的手机号" : "",
                                helperStyle: TextStyle(
                                    color: ColorUtil.color("#FFFF0000"),
                                    fontSize: 12),
                                focusedBorder: UnderlineInputBorder(
                                    borderSide: BorderSide(color: Colors.grey)),
                                hintStyle: TextStyle(
                                    color: ColorUtil.color("#FF999999"),
                                    fontSize: 15)),
                            onChanged: _textFieldChanged),
                      ),
                    )),
                // 清除按钮
                Material(
                  child: phoneController.text != ''
                      ? IconButton(
                          icon: Icon(Icons.clear),
                          onPressed: () {
                            setState(() {
                              phoneController.text = '';
                              isActive = false;
                              error = false;
                            });
                          },
                        )
                      : null,
                )
              ],
            ),
            // // 按钮
            MBtn(
              function: () {
                _getCode(context);
              },
              title: '下一步',
              btnWidth: 325,
              btnHeight: 47,
              borderRadius: 5,
              hasBg: true,
              textColor: isActive ? textActiveColor : textDefaultColor,
              bgColor: isActive ? btnActiveColor : btnDefaultColor,
              borderColor: isActive ? btnActiveColor : btnDefaultColor,
            ),
          ],
        ),
      ),
    );
  }

  // 输入框改变的回调
  void _textFieldChanged(String value) {
    if (value.length < 11) {
      setState(() {
        isActive = false;
      });
    } else {
      setState(() {
        isActive = true;
      });
    }
  }

  // 点击按钮下一步，发送验证码，并跳转页面
  void _getCode(BuildContext context) {
    final phoneNum = phoneController.text;
    if (phoneNum.length < 11) {
      return;
    }
    // 校验手机号的合法性
    if (!isMobilePhoneNumber(phoneNum)) {
      setState(() {
        error = true;
      });
      ShowToast.toast(context, msg: '请输入合法手机号', position: ToastPostion.center);
      return;
    }
    // 加载弹窗
    showLoadingDialog(context);
    // 请求接口数据
    CommonDao.GetCode(phoneNum).then((PhoneCodeModel model) => {
          // 关闭弹窗
          Navigator.pop(context),
          if (model.status == 200)
            {
              // 将手机号存起来
              context.read<LoginPhoneProvider>().setLoginPhone(phoneNum),
              // 提示
              ShowToast.toast(context,
                  msg: "验证码发送成功", position: ToastPostion.center),

              // 页面跳转
              if (model.data == 1)
                {
                  //手机号已注册
                  Navigator.push(
                      context,
                      MaterialPageRoute(
                          builder: (context) => InputCode(
                                title: '登录',
                                phoneNum: phoneNum,
                              )))
                }
              else
                {
                  // 手机号没有注册
                  Navigator.push(
                      context,
                      MaterialPageRoute(
                          builder: (context) => InputCode(
                                title: '注册',
                                phoneNum: phoneNum,
                              )))
                }
            }
          else
            {
              // 提示
              ShowToast.toast(context,
                  msg: model.msg, position: ToastPostion.center),
            }
        });
  }
}
